package com.aisoback.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aisoback.model.Picture;
import com.aisoback.service.PictureService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> getPictureList(String searchText, int pageNum, int pageSize) throws IOException {
        System.out.println("开始爬取图片");
        String url = "https://cn.bing.com/images/search?q=" + searchText + "&form=HDRSC2&first=" + pageNum + "&cw=1177&ch=736";
        Document doc = Jsoup.connect(url).get();
        List<Picture> pictures = new ArrayList<>();
        Elements elements = doc.select(".iuscp.isv");
        for (Element element : elements) {
            // 获取图片的url
            String m = element.select(".iusc").attr("m");
            //将获取的数据对象转换成json对象
            JSONObject jsonObject = JSONUtil.parseObj(m);
            //从json对象中获取图片在html中的url地址
            String murl = jsonObject.getStr("murl");
            System.out.println(murl);
            //获取图片的title
            String title = element.select(".inflnk").attr("aria-label");
            System.out.println(title);
            Picture picture = new Picture();
            picture.setUrl(murl);
            picture.setTitle(title);
            pictures.add(picture);
            System.out.println("爬取完成");
        }
        Page<Picture> picturepage = new Page<>();
        picturepage.setRecords(pictures);
        return picturepage;

    }

}
